<template>
<div>
  <h1>userset</h1>


  <el-form :model="register" label-width="100px">
    <el-form-item label="头像" >
      <el-upload
          class="avatar-uploader"
          ref="upload"
          action="#"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="handleChange"
          :on-change="onChange"
          :auto-upload="false"
          :data="addList">
        <img v-if="header_pic" :src="header_pic" class="avatar" style="width: 100px" alt>
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <el-divider></el-divider>
  </el-form>
  <el-form :model="register" label-width="100px" :rules="rules" ref="ruleForm">
    <el-form-item label="用户名" prop="username">
      <el-input type="text" v-model="register.username" :disabled="true"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="register.password" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="passwordCheck">
      <el-input type="password" v-model="register.passwordCheck" autocomplete="off"></el-input>
    </el-form-item>

    <span style="color: red">{{msg}}</span>
    <el-button @click="submit">修改密码</el-button>
  </el-form>
</div>

</template>

<script>
import {mapState} from "vuex";
import {reqPostUpdateUserHeader} from "@/api/user";
import { requestIsSuccess} from "@/api/request";

export default {
  name: "UserSet",
  data(){
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      }else if(this.register.passwordCheck !=='' && this.register.passwordCheck!==value){
        callback(new Error('两次输入密码不一致!'));
      } else {
        if (this.register.password !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.register.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return{
      register:{
        username:this.$store.getters.username,
        password:'',
        passwordCheck:'',
      },
      header_pic:this.$store.getters.avatar,
      addList:{},
      imageUrl:'',
      rules:{
        username:[
          {required:true,message:'请输入用户名',trigger:'blur'},
          {min:3,max:10,message:'长度为3到10',trigger: 'blur'}
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        passwordCheck: [
          { validator: validatePassCheck, trigger: 'blur' }
        ],
      },
      msg:''
    }
  },
  computed:{
    ...mapState({
      userInfo: (state)=>state.user.userInfo
    })
  },
  methods:{

    beforeUpload(){
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    onChange(file,fileList){
      var _this = this;
      var event = event || window.event;
      var file = event.target.files[0];
      var reader = new FileReader();
      //转base64
      reader.onload = function(e) {
        _this.header_pic = e.target.result //将图片路径赋值给src
      }
      reader.readAsDataURL(file);
    },
    handleChange(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    submit(){
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const result = await this.$store.dispatch('userSetPassword', this.register.password)
          if (result == true) {
            await this.$router.push('/login');
            this.successMessage("密码已经修改")
          }
        }
      })
    }
  },
    watch:{
    header_pic:{
      handler(value,oldValue){
        console.log(value,oldValue)
        if(value!==''){
          const data={
            header_pic:value
          }
          reqPostUpdateUserHeader(data).then(res => {
            if(requestIsSuccess(res)){
              this.$store.dispatch("clearUserinfo")//清空登录信息
              this.successMessage("更新头像成功")
            }
          }).catch(ex=>{
            this.warningMessage(ex.message)
          })
        }

      },

    }
  }
}
</script>

<style scoped>

</style>